package org.lyh.base.service.impl;

import org.lyh.base.mapper.BaseMapper;
import org.lyh.base.query.BaseQuery;
import org.lyh.base.service.IBaseService;
import org.lyh.base.util.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Objects;

@Service
@Transactional(propagation = Propagation.SUPPORTS,readOnly = true)
public class BaseServiceImpl<T> implements IBaseService<T> {
    @Autowired
    private BaseMapper<T> baseMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public T queryOne(Long id) {
        return baseMapper.selectById(id);
    }

    @Override
    public List<T> queryList() {
        Object departmentList = redisTemplate.opsForValue().get("departmentList");
        if (Objects.isNull(departmentList)){
            List<T> ts = baseMapper.selectAll();
            redisTemplate.opsForValue().set("departmentList",ts);
            return ts;
        }
        return (List<T>) departmentList;
    }

    @Transactional
    @Override
    public void addOne(T department) {
        baseMapper.insert(department);
    }
    @Transactional
    @Override
    public void deleteById(Long id) {
        baseMapper.deleteById(id);
    }

    @Transactional
    @Override
    public void updateOne(T department) {
        baseMapper.update(department);
    }

    @Override
    @Transactional
    public void batchDelete(List<Long> ids) {
        baseMapper.batchDelete(ids);
    }

    @Override
    public PageInfo<T> queryPage(BaseQuery dto) {
        PageInfo<T> pageInfo = new PageInfo<>();
        Long total = baseMapper.getTotal(dto);
        if (total > 0) {
            pageInfo.setTotal(total);
            List<T> t = baseMapper.queryPage(dto);
            pageInfo.setList(t);
        }
        return pageInfo;
    }
}
